package com.example.mqttclient;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class WeatherApi {
    private static final String API_BASE_URL = "https://api.seniverse.com/v3/weather/now.json?key=SgB4r3To_mXqzeTia&location=beijing&language=zh-Hans&unit=c "; // 替换为真实的 API 地址
    private static final String API_KEY = "PGbpf3G8AwqcL1JLT"; // 替换为真实的 API 密钥
    private static OkHttpClient client = new OkHttpClient();

    public WeatherApi() {
        this.client = new OkHttpClient();
    }

    /**
     * 获取指定城市的天气数据
     * @param city 城市名称
     * @return 包含天气信息的 JSONObject
     * @throws IOException 如果网络请求失败
     * @throws JSONException 如果 JSON 解析失败
     */
    public static String getWeatherInfo(String city) {
        try {
            String url = String.format("%s?key=%s&location=%s&language=zh-Hans&unit=c",
                    API_BASE_URL, API_KEY, city);

            Request request = new Request.Builder()
                    .url(url)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("API 请求失败：" + response.code());

                String responseData = response.body().string();
                JSONObject json = new JSONObject(responseData);

                JSONObject results = json.getJSONArray("results").getJSONObject(0);
                String text = results.getString("now_text");
                String temperature = results.getString("now_temp");
                return String.format("当前天气：%s，温度：%s°C", text, temperature);
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return "天气信息获取失败";
        }
    }
}
